var route = {
    num: false,
    startPoint: null,
    endPoint: null,
    routingLayer: null,
    startMarker: null,
    endMarker: null
};

initRoutingControlUI();

/**
 * 添加路径规划图标
 */
function initRoutingControlUI() {
    var layerIcon = $('<div class="route" onclick="startRouting()"></div>');
    $('#toolPanel').append(layerIcon);
}

/**
 * 开始路径导航
 */
function startRouting() {
    if (map.hasLayer(route.routingLayer)) {
        clearPath();
        map.removeEventListener("click");
        return;
    }
    map.fitBounds([[34.825008392334, 113.557716369629],
        [34.8254280090332, 113.558219909668]]);
    map.addEventListener("click", function (e) {
        if (route.num) {
            route.endPoint = [e.latlng.lng, e.latlng.lat];
            route.num = false;
            route.endMarker = addMarker(e.latlng.lat, e.latlng.lng, "end.png");
            var viewParams = [
                'x1:' + route.startPoint[0], 'y1:' + route.startPoint[1],
                'x2:' + route.endPoint[0], 'y2:' + route.endPoint[1]
                , 'fnumber:'+layerManager.getCurrentFloor()
            ];

            route.routingLayer = L.tileLayer.wms(mapSource.Route.url, {
                layers: mapSource.Route.layer,
                crs: L.CRS.EPSG4326,
                format: 'image/png',
                transparent: true,
                maxZoom: 40,
                minZoom: 14,
                viewparams: viewParams.join(";")
            }).addTo(map);

        } else {
            clearPath();
            route.num = true;
            route.startPoint = [e.latlng.lng, e.latlng.lat];
            route.startMarker = addMarker(e.latlng.lat, e.latlng.lng, "start.png");
        }
    })
}


/**
 * 标记地图
 */
function addMarker(lat, lng, str) {
    var marPath = "../../img/" + str;
    var myIcon = L.icon({
        iconUrl: marPath,
        iconSize: [45, 45],
        iconAnchor: [22, 45],
        popupAnchor: [-3, -76],
        shadowSize: [68, 95],
        shadowAnchor: [22, 94]
    });
    var marker = L.marker([lat, lng], {icon: myIcon}).addTo(map);
    return marker;
}


/**
 * 清除最短路径结果
 */
function clearPath() {
    if (map.hasLayer(route.routingLayer)) {
        map.removeLayer(route.routingLayer);
        map.removeLayer(route.startMarker);
        map.removeLayer(route.endMarker);
    }
    route.startPoint = null;
    route.endPoint = null;
    route.num = false;
}